from odoo import fields, models, api, _
from odoo.exceptions import ValidationError


class SaleVersionChange(models.Model):
    _name = 'sale.version.change'

    def _default_name(self):
        return self.env['ir.sequence'].next_by_code('sale.version.change')

    name = fields.Char(string='Ref', default=_default_name)
    change_apply_id = fields.Many2one('sale.change.apply', string='Change Apply')
    order_type = fields.Selection(related="change_apply_id.order_type", string='Order Change')
    partner_id = fields.Many2one('res.partner', related="change_apply_id.partner_id", string='Custom')
    product_tmpl_id = fields.Many2one('product.template', related="change_apply_id.product_tmpl_id", string="Product Custom")
    code = fields.Char(related="change_apply_id.code",string='PN')
    version = fields.Char(related="change_apply_id.version",string='Version')
    line_ids = fields.One2many('sale.version.change.line', 'parent_id')
    state = fields.Selection([('draft', 'Draft'), ('confirm', 'Confirm')],  default='draft', string='Status')

    @api.onchange('change_apply_id')
    def onchange_line_ids(self):
        line_vals = []
        self.line_ids = None
        for line in self.change_apply_id.line_ids:
            product_tmpl_id = line.c_product_tmpl_id
            product = self.env['product.product'].sudo().search([('product_tmpl_id', '=', product_tmpl_id.id)])
            line_vals.append((0, 0, {
                'sale_order_id':line.sale_order_id,
                'order_line':line.order_line.id,
                'product_tmpl_id': line.c_product_tmpl_id.id,
                'product_v2': product.id,
                'version_v2': line.c_version,
                'code_v2': line.c_pn.code
            }))
        self.line_ids = line_vals

    def button_confirm(self):
        if not self.line_ids.filtered(lambda x: x.product_v2):
            ValidationError(_('Please select a replacement product'))

        reset_confirm_sale = []
        cancel_pickings = []
        for line in self.line_ids:
            if line.order_line.s_mrp_production_ids:
                raise ValidationError(_("请先断开工单连接后，再执行暂停销售订单"))

            order_line = line.order_line
            if line.product_id == line.product_v2:
                raise ValidationError(_("You cannot select the same product"))
            if line.sale_order_id.delivery_status == 'full':
                raise ValidationError(_("The sales order has been delivered"))
            if line.sale_order_id.state in ['draft', 'sent']:
                order_line.product_id = line.product_v2.id
            elif line.sale_order_id.state == 'cancel':
                raise ValidationError(_("The sales order has been cancel"))
            else:
                price_unit = order_line.price_unit
                picking_ids = line.sale_order_id.picking_ids.filtered(lambda x: x.state not in ['done', 'cancel'])
                cancel_pickings.extend([picking for picking in picking_ids])
                if line.sale_order_id not in reset_confirm_sale:
                    reset_confirm_sale.append(line.sale_order_id)

                order_line.with_context(ecr_apply=True).update({
                    'price_unit': price_unit,
                    'product_id': line.product_v2.id,
                    'pn': line.code_v2,
                    'pn_rev': line.version_v2,
                })

        for picking in cancel_pickings:
            picking.with_context(ecr_apply=True).action_cancel()
            # picking.is_lock = False
            picking.active = False

        for sale in reset_confirm_sale:
            sale.with_context(ecr_apply=True).version_action_confirm()
            # sale.is_lock = False
            # for mrp in sale.option_mrp_production_ids:
                # mrp.is_lock = False
        tree_id = self.env.ref('sale.view_order_tree').id
        form_id = self.env.ref('sale.view_order_form').id
        self.state = 'confirm'
        return {
            'name': 'Rework',
            'type': 'ir.actions.act_window',
            'view_type': 'form',
            'view_mode': 'form, tree',
            'res_model': 'sale.order',
            'domain': [('id', 'in', [sale.id for sale in reset_confirm_sale])],
            'views': [(tree_id, 'tree'), (form_id, 'form')],
            'context': {'create': 0},
        }


class SaleVersionChangeLine(models.Model):
    _name = 'sale.version.change.line'
    
    parent_id = fields.Many2one('sale.version.change')
    # 销售订单
    sale_order_id = fields.Many2one('sale.order', string='Sale Order')
    # 销售订单行
    order_line = fields.Many2one('sale.order.line', string='Sale Order Line')
    product_id = fields.Many2one('product.product', string='Product', related='order_line.product_id')
    product_v2 = fields.Many2one('product.product', string='Target Product')
    code_v2 = fields.Char(string='Target PN')
    version_v2 = fields.Char(string='Target Version')
    product_tmpl_id = fields.Many2one('product.template', string="Customer Part")

    # @api.onchange('product_tmpl_id')
    # def onchange_product_v2(self):
    #     product_tmpl_id = self.product_tmpl_id
    #     version_v2 = None
    #     code_v2 = None
    #     if not product_tmpl_id or not product_tmpl_id.customer_item_code_ids:
    #         pass
    #     else:
    #         customer_item_code_ids = product_tmpl_id.customer_item_code_ids
    #         version_v2 = customer_item_code_ids[0].version
    #         code_v2 = customer_item_code_ids[0].code
    #     self.version_v2 = version_v2
    #     self.code_v2 = code_v2
    #     self.product_v2 = self.product_tmpl_id.product_variant_id.id